package com.longrise.android.byjk.plugins.vip.integralexchange;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.base.BaseFragment;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.IntegralExchangeRefreshEvent;
import com.longrise.android.byjk.event.MineRefreshEvent;
import com.longrise.android.byjk.event.MyIntegralEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalExhibitionActivity;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by callxkj on 2017/7/22.
 * 积分兑换中的展业秀背景
 */

public class IExchangezyxbgFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener, OnIntegralExchangeRcvItemClickListener {

    private BBswipeRefreshLayout mBbsrl;
    private RecyclerView mRcv;
    private IExchangezyxbgAdapter mAdapter;
    private int mPosition;  //google跟踪使用

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_iexchangezyxbg;
    }

    @Override
    public void initView() {
        mBbsrl = (BBswipeRefreshLayout) mRootView.findViewById(R.id.iexchagezyxbg_srl);
        mRcv = (RecyclerView) mRootView.findViewById(R.id.iexchagezyxbg_rcv);
        EventBus.getDefault().register(this);
        initRcv();
        initEvent();
        getData();
    }

    private void initEvent() {
        mBbsrl.setOnRefreshListener(this);
        mAdapter.setOnRcvItemClickListener(this);
    }


    private void initRcv() {
        View headView = View.inflate(mContext, R.layout.item_rcv_integralexchange_head, null);
        mAdapter = new IExchangezyxbgAdapter("背景兑换");
        mAdapter.addHeaderView(headView);
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
        mRcv.setLayoutManager(layoutManager);
        mRcv.setAdapter(mAdapter);
    }


    /**
     * 获取展示的数据
     */
    private void getData() {
        mBbsrl.setRefreshing(true);
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean fbean = new EntityBean();
        String serverName = "";
        serverName = "bbt_vip_sGoodsInfobygoodstype";
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, serverName, fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    String resultdesc = bean.getString("resultdesc");
                    int value = (Integer) bean.get("resultstate");
                    if (value == 1) {
                        EntityBean[] results = bean.getBeans("result");
                        parseResult(results);
                    } else {
                        showToast(resultdesc);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                refreshComplete();
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }
        });
    }

    private void parseResult(EntityBean[] beans) {
        EntityBean bean = beans[0];
        EntityBean[] goodsinfos = bean.getBeans("goodsinfo");
        String goodstype = bean.getString("goodstype");
        mAdapter.setDatas(goodsinfos, goodstype);
    }

    private void refreshComplete() {
        mBbsrl.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        getData();
    }

    @Override
    public void onClick(int type, String lockstate, String goodsid, String goodstype, String needscores, String imageUrl, String detailpicurl, int position) {
        this.mPosition = position;
        switch (type) {
            case 1:
                toTextClick(lockstate, goodsid, goodstype, needscores);
                break;
            case 2:
                toImageClick(imageUrl, lockstate, needscores, detailpicurl, goodsid, goodstype);
                break;
        }
    }

    /**
     * 点击的是图片
     */
    private void toImageClick(String imageUrl, String lockstate, String needscores, String detailpicurl, String goodsid, String goodstype) {
        Bundle bundle = new Bundle();
        bundle.putString(IntegralExchangeImageActivity.IMAGEURL_INTENT, imageUrl);
        bundle.putString(IntegralExchangeImageActivity.LOCKSTATE_INTENT, lockstate);
        bundle.putString(IntegralExchangeImageActivity.NEEDSCORS_INTENT, needscores);
        bundle.putString(IntegralExchangeImageActivity.DETAILPICURL_INTENT, detailpicurl);
        bundle.putString(IntegralExchangeImageActivity.GOODSID_INTENT, goodsid);
        bundle.putString(IntegralExchangeImageActivity.GOODSTYPE_INTENT, goodstype);
        bundle.putInt(IntegralExchangeImageActivity.CURRENT_BACK_POSTION, mPosition);  //当前背景position
        bundle.putInt(IntegralExchangeImageActivity.PAGE_FROM_FLAG, IntegralExchangeImageActivity.PAGE_FROM_MYINTEGRAL);
        Intent intent = new Intent(mContext, IntegralExchangeImageActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

    /**
     * 点击的是文字
     */
    private void toTextClick(String lockstate, String goodsid, String goodstype, String needscores) {
        if ("1".equals(lockstate)) { //解锁状态  1:已解锁  0：未解锁
            toChangeSkin(goodsid);
        } else if ("0".equals(lockstate)) {
            checkIsEnoughIntegral(goodsid, goodstype, needscores);

        }
    }


    /**
     * 检查积分是否充足
     */
    private void checkIsEnoughIntegral(final String goodsid, final String goodstype, final String needscores) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("goodsid", goodsid);
        bean.set("goodstype", goodstype);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_isEnoughCostgoods", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int resultstate = (Integer) bean.get("resultstate");
                            if (resultstate == 1) { //积分充足
                                IntegralExchangeDialogHelper.toShowIntegralExchangeDialog((BaseActivity) getActivity(),
                                        goodsid, goodstype, needscores,
                                        new IntegralExchangeDialogHelper.ToIntegralExchangeListener() {
                                            @Override
                                            public void toIntegralExchange(String goodsid, String goodstype) {
                                                togetIntegralExchange(goodsid, goodstype);
                                            }
                                        });
                            } else if (resultstate == 2) { //积分不足
                                IntegralExchangeDialogHelper.showIntegralnotenoughtDialog((BaseActivity) getActivity());
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                    }
                });
    }


    /**
     * 积分兑换
     */
    private void togetIntegralExchange(String goodsid, String goodstype) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("goodsid", goodsid);
        bean.set("goodstype", goodstype);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_iScoresCostRecord", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int value = (Integer) bean.get("resultstate");
                            if (value == 1) { //积分兑换成功
                                showToast(resultdesc);
                                onRefresh();
                                EventBus.getDefault().post(new MyIntegralEvent(true));
                                MineRefreshEvent mineRefreshEvent = new MineRefreshEvent();
                                mineRefreshEvent.setBBye(true);
                                EventBus.getDefault().post(mineRefreshEvent); //我的页面保宝余额与我的积分是同一个接口
                            } else if (value == 2) { //积分不足
                                IntegralExchangeDialogHelper.showIntegralnotenoughtDialog((BaseActivity) getActivity());
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }


    /**
     * 换肤
     */
    private void toChangeSkin(String goodsid) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("skinid", goodsid);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_uVIPstateBySkinid", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    String resultdesc = bean.getString("resultdesc");
                    int value = (Integer) bean.get("resultstate");
                    if (value == 1) {
                        onRefresh();
                        Intent intent = new Intent(mContext, PersonalExhibitionActivity.class);
                        getActivity().startActivity(intent);
                    } else {
                        showToast(resultdesc);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                dismissLoadingDialog();
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toRefresh(IntegralExchangeRefreshEvent bean) {
        if (bean.ismIsneedfinish()) {
            getActivity().finish();
        } else {
            onRefresh();
        }

    }

    /**
     * 显示网络加载dialog
     */
    public void showLoadingDialog() {
        DZZWTools.showWaitDialog(mContext);
    }

    /**
     * 隐藏网络加载dialog
     */
    public void dismissLoadingDialog() {
        DZZWTools.dismissDialog(null);
    }





    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
